/**
 * 
 */
package info.niwota.webime.web;

import info.niwota.commons.acl.AccessControl;
import info.niwota.commons.web.AjaxObject;
import info.niwota.webime.Debug;
import info.niwota.webime.WebInputActivity;
import info.niwota.webime.WebInputApplication;
import info.niwota.webime.WebKeyboardService;

import org.json.JSONObject;

import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

/**
 * @author qiangli
 * 
 */
public class WebIMEObject extends AjaxObject {

	public static final String NAME = "webime";

	private static final String TAG = "WebIMEObject";

	public WebIMEObject(Context ctx) {
		super(ctx);
	}

	public Object updateInput(JSONObject param, Uri uri) throws Exception {
		if (Debug.DEBUG) {
			Log.d(TAG, "updateInput param: " + param + " uri: " + uri);
		}
		String label = Label.LABEL_WEB_IME;
		String group = uri.getQueryParameter("group");
		String user = uri.getQueryParameter("user");

		int g = (TextUtils.isEmpty(group) ? AccessControl.ACCESS_PUBLIC
				: Integer.parseInt(group));

		JSONObject jo = new JSONObject();

		//
		if (!canAccess(g, user, label)) {
			//throw new Exception("Accessed denied");
			jo.put("rc", false);
			jo.put("error", "Accessed denied");
			return jo;
		}

		String action = uri.getQueryParameter("action");
		String input = uri.getQueryParameter("input");

		Log.d(TAG, "action: "+ action + " input [" + input + "]");

		//
		WebInputApplication appctx = (WebInputApplication) ctx
				.getApplicationContext();

		WebInputActivity pad = appctx.pad;
		if (pad != null) {
			//pad ignores action and only updates text input
			boolean rc = pad.updateInput(1, input);
			jo.put("rc", rc);
			jo.put("error", null);
			return jo;
		}
		
		WebKeyboardService kbs = appctx.ime;
		if (kbs != null) {
			boolean rc = kbs.updateInput(action, input);
			jo.put("rc", rc);
			jo.put("error", null);
			return jo;
		}
		
		jo.put("rc", false);
		jo.put("error", "Web Input application/IME not active");
		
		return jo;
	}

	protected int toInt(String s, int def) {
		try {
			return Integer.parseInt(s);
		} catch (Exception e) {
			
		}
		return def;
	}

	protected boolean isLocal(Uri uri) {
		String peer = uri.getQueryParameter("peer");
		String jid = uri.getQueryParameter("jid");
		return TextUtils.isEmpty(peer) || peer.equals(jid);
	}

}
